<?php
/**
 * 视频控制器
 *
 * @author susy<susy.liang@ilongyuan.com.cn>
 */

/***************change log *******************
+----栏目视频换一批 susy.laing<liangling@ilongyuan.com.cn> at 2015/7/6
*********************************************/

namespace Home\Controller;

class VideoController extends HomeController {

    /**
     * 栏目视频Id集
     */
    static $topicVids;

    /**
     * 栏目对象
     */
    protected $tEvent = '';

    /**
     * 视频对象
     */
    protected $vEvent = '';

    /**
     * 基础参数的初始化
     */
    protected function _initialize() {

        parent::_initialize();

        $this->tEvent = A( 'Api/Topic', 'Event' );
        $this->vEvent = A( 'Api/Video', 'Event' );

    }

    /**
     * 列表栏目首页
     */
    public function index() {
        $this->id = $id = I( 'id', 0, 'intval' );

        $topic = $this->tEvent->info( $id );
        if ( empty( $topic ) )
            $this->error( '栏目信息有误' );

        $this->topicTitle = $topic['title'];

        $listInfo = $this->getTopicList( $id );

        $this->content = $listInfo['content'];

        $this->display();
    }


    /**
     * 获取该栏目类下的视频数据
     */
    private function getTopicList( $id, $timestamp=0 ) {

        $listRow = C( 'VIDOE_LIST_ROWS' );

        $data = array( 'content'=>'', 'total'=>0, 'limit'=>$listRow );

        $listVideo = $this->tEvent->getVideos( $id, $listRow, $timestamp );

        $filterMap = array( 'id', 'title', 'thumb', 'pre_uri', 'uri', 'create_time', 'detail', 'user', 'statis', 'action', 'time');
        $this->data = $listVideo = $this->lists_format( $listVideo, $filterMap );

        if ( $listVideo ) {
            $count = count( $listVideo );
            $this->timestamp = $listVideo[$count-1]['timestamp'];

            $strhtml = $this->fetch( 'Template:video' );
            $data['content'] = $strhtml;
            $data['total'] = count( $listVideo );
        }

        return $data;
    }

    /**
     * 栏目下的视频列表
     */
    public function ajaxList() {

        $id = I( 'id', 0, 'intval' );
        $timestamp = I( 'timestamp', '', 'strip_tags' );

        if ( empty( $id ) || empty( $timestamp ) )
            $this->ajaxReturn( array( 'state'=>-1, 'info'=>'参数有误' ) );

        $topic = $this->tEvent->info( $id );
        if ( empty( $topic ) )
            $this->ajaxReturn( array( 'state'=>-1, 'info'=>'栏目信息有误' ) );

        $listInfo = $this->getTopicList( $id, $timestamp );

        $this->ajaxReturn( array( 'state'=>0, 'info'=>'操作成功', 'data'=>$listInfo ) );

    }

    /**
     * 最热视频列表
     */
    public function hot() {

        $play = I( 'play', 0 );
        $listRow = C( 'VIDOE_LIST_ROWS' );
        $videoId = $this->vEvent->getHot( $listRow, $play );

        $filterMap = array( 'id', 'title', 'thumb', 'pre_uri', 'uri', 'create_time', 'detail', 'user', 'statis', 'action', 'time' );
        $this->data = $listVideo = $this->lists_format( $videoId, $filterMap );
        if ( $listVideo ) {
            $count = count( $listVideo );
            $this->timestamp = $listVideo[$count-1]['timestamp'];

            $this->play = $listVideo[$count-1]['statis']['play'];
            $strhtml = $this->fetch( 'Template:video' );
        }

        if ( IS_AJAX ) {

            $this->ajaxReturn( array( 'state'=>0, 'info'=>'请求成功',
                    'data'=>array( 'content'=>$strhtml, 'total'=>count( $listVideo ), 'limit'=>$listRow ) ) );
        }else {

            $this->ajaxUrl = U( 'Video/hot' );
            $this->topicTitle = '最热视频';
            $this->content = $strhtml;

            $this->display( 'index' );
        }

    }

    /**
     * 最新视频列表
     */
    public function latest() {

        $timestamp = I( 'timestamp', 0, 'intval' );
        $listRows = C( 'VIDOE_LIST_ROWS' );
        $videoId = $this->vEvent->getNew( $listRows, $timestamp );
        $filterMap = array( 'id', 'title', 'thumb', 'pre_uri', 'uri', 'create_time', 'detail', 'user', 'statis', 'action', 'time');
        $this->data = $listVideo = $this->lists_format( $videoId, $filterMap );
        if ( $listVideo ) {
            $count = count( $listVideo );
            $this->timestamp = $listVideo[$count-1]['timestamp'];

            $strhtml = $this->fetch( 'Template:video' );
        }

        if ( IS_AJAX ) {
            $this->ajaxReturn( array( 'state'=>0, 'info'=>'请求成功',
                    'data'=>array( 'content'=>$strhtml, 'total'=>count( $listVideo ), 'limit'=>$listRows ) ) );
        }else {

            $this->ajaxUrl = U( 'Video/latest' );
            $this->topicTitle = '最新视频';
            $this->content = $strhtml;

            $this->display( 'index' );
        }
    }


    /**
     * 列表
     */
    public function play() {
        $this->id = $id = I( 'id', 0, 'intval' );
        $type = I( 'type' );

        if (isset($type) && $type =='share'){
            // C( 'LOCAL_DOMAIN' ).'/index.php#/video/'.$id;
            $this->redirect('Home/Share/video',['id'=> $id ]);
            return;
        }

        $vEvent = A( 'Api/Video', 'Event' );
        //$uid = is_login(1);

        $video = $vEvent->detail( $id, UID );
        if ( !$video ) {
            $this->error( '视频信息有误' );
        }

        $vEvent->setPlay( $id );
        A( 'Api/History', 'Event' )->add( UID, $id );

        $lEvent = A( 'Api/Like', 'Event' );
        $this->likeUser = $lEvent->getUser( $id, 6 );

        $commentData = $this->getComment( $id, 0, false );
        $this->comments = $commentData['content'];

        $this->data = $video;
        if ( $type && $type=="share" ) {

            if ( is_mobile_request() ) {
                $filterMap = array( 'id', 'title', 'thumb', 'pre_uri', 'uri', 'detail', 'user', 'statis', 'action', 'time' );
                $newVideo = $vEvent->getNew( C( 'VIDEO_INDEX_LIMIT' ) );
                $newVideo = $this->lists_format( $newVideo, $filterMap );
                $this->newVideo = $newVideo;
                $this->display();
            }
            else {
                $url = U('Home/Share/video',['id'=> $id ]);// C( 'LOCAL_DOMAIN' ).'/index.php#/video/'.$id;
                $this->redirect($url);
            }
        }else {

            if ( $this->likeUser ) {
                $this->strLiker = $this->fetch( 'Template:liker' );
            }
            $strhtml = $this->fetch( 'Template:play' );
            $this->ajaxReturn( array( 'state'=>0, 'data'=>array( 'content'=>$strhtml ) ) );
        }
    }


    /**
     * 视频评论
     */
    public function comments() {
        $vid = I( 'vid', 0, 'intval' );

        //$uid = IS_LOGIN(1);
        // 游客评论 by liubo at 2016-05-24
        if ( !UID ) {
            // 上次评论时间
            $lastCommentTime = cookie('lastCommentTime_'.$vid);
            if (!empty($lastCommentTime)) {
                $this->ajaxReturn(['state' => -3, 'info' => '操作过于频繁，请稍候重试']);
            }
            // 60秒有效
            cookie('lastCommentTime_'.$vid, time(), 60);
        }

        $eventObj = A( 'Api/Comments', 'Event' );

        $content = I( 'comment' );
        $user = array(
            'uid'=>UID,
            'nickname'=>session( 'home_user_auth.nickname' )
        );

        $flg = $eventObj->add( $vid, $user, $content );

        $state = -1;
        switch ( $flg ) {
        case 1:
            $info ='非法视频';
            break;
        case 2:
            $info = '评论不能为空';
            break;
        case 3:
            $info = '评论失败';
            break;
        default :
            $state = 0;
            $info = '评论成功';
            break;
        }

        if ( !$state ) {

            $video = A( 'Api/Video', 'Event' )->detail( $vid, 0, false );

            $msgReply = I( 'reply' );
            if ( $msgReply ) {
                //modify by susy.liang 与我相关页的用户评论的修改 2015/7/2
                /* $referCmt = $eventObj->get($vid, '', '', array('referrer'=>UID), false, false);
                foreach ($referCmt as $key => $value) {
                    $referCmt[$key]['unixtime'] = $value['create_time'];
                    $referCmt[$key]['create_time'] = unixtime_format($value['create_time']);
                }

                $selfCmt = $eventObj->get($vid, '', '', array('uid'=>UID), false, false);
                foreach ($selfCmt as $key => $value) {
                    $selfCmt[$key]['unixtime'] = $value['create_time'];
                    $selfCmt[$key]['create_time'] = unixtime_format($value['create_time']);
                }

                $this->comments = aggreateCmt($referCmt, $selfCmt);

                $strComment = $this->fetch('Video:comment');
                $data['content'] = $strComment;*/

                if ( $video['uid'] == UID ) {
                    $this->comments = $eventObj->get( $vid, 5, '', array(), true, false );
                }else {
                    $query = array();
                    $cmtMap = array();
                    $where = array();

                    $query[]['uid']     = array( '$eq'=>intval( UID ) );
                    $query[]['referrer'] =  array( '$eq'=>intval( UID ) );
                    $cmtMap['$and'][]['$or'] = $query;
                    $cmtMap['$and'][]['video_id'] = intval( $vid );
                    $where['_array'] = $cmtMap;

                    $this->comments = $eventObj->get( 0, '', '', $where, true );

                }
                $data['content'] = $this->fetch( 'Video:comment' );
                //end

            }else {
                $data = $this->getComment( $vid );
                $data['all'] = $video['statis']['comments'];
            }

        }

        $this->ajaxReturn( array( 'state'=>$state, 'info'=>$info, 'data'=>$data ) );
    }

    /**
     * 获取评论信息
     * 用于评论的加载
     */
    public function ajaxComment() {

        $vid = I( 'vid', 0, 'intval' );
        $timestamp = I( 'timestamp', 0, 'intval' );

        if ( empty( $vid ) )
            $this->ajaxReturn( array( 'state'=>-1, 'info'=>'参数有误' ) );

        $data = $this->getComment( $vid, $timestamp );

        $this->ajaxReturn( array( 'state'=>0, 'info'=>'请求成功', 'data'=>$data ) );
    }

    /**
     * 获取评论列表
     * 参数：vid(视频Id), pager(每页数量), p(页码)
     * @author liubo <liubo@ilongyuan.com.cn>
     */
    // 热门评论 type=hot  liubo 2016-7-28
    public function getCommentList() {
        $vid = I('request.vid', 0, 'intval');
        $p = I('request.p', 1, 'intval');
        $pager = I('request.pager', C( 'COMMENT_LIST_ROWS' ), 'intval');

        $cEvent = A( 'Api/Comments', 'Event' );

        $type = I('request.type', '', 'trim');

        $map = [];
        if ($type == 'hot') {
            $map['zan'] = ['$gt' => 0];
            $list = $cEvent->getHot($vid, $p, $pager, true, UID);
        } else {
            $list = $cEvent->getByPager($vid, $p, $pager, UID);
        }

        if ($list) {
            $list = array_map(function($comment) {
                $comment['content'] = htmlspecialchars($comment['content']);
                return $comment;
            }, $list);
        }

        $total = $cEvent->getCommentCount($vid, $map);
        $response = [
            'state' => 0,
            'info'  => '请求成功',
            'data'  => $list ?: [],
            'total' => $total
        ];

        $response['data'] = $list;
        $this->ajaxReturn($response);
    }

    /**
     * 评论获取,用于内部调用
     */
    public function getComment( $vid, $timestamp=0, $tohtml=true ) {

        $listRow = C( 'COMMENT_LIST_ROWS' );
        $data = array( 'content'=>'', 'total'=>0, 'limit'=>$listRow );

        $cEvent = A( 'Api/Comments', 'Event' );
        $field = "id,uid,nickname,content,create_time";

        $filter = array();
        if ( $timestamp )
            $filter['create_time'] = array( 'lt', $timestamp );

        $arrData = $cEvent->get( $vid, $listRow, $field, $filter, true, true );
        $comments = $arrData['data'];
        $this->timestamp = $arrData['timestamp'];

        if ( $comments ) {
            $comments = array_map(function($comment) {
                $comment['content'] = htmlspecialchars($comment['content']);
                return $comment;
            }, $comments);
            $data['total'] = count( $comments );
            if ( $tohtml ) {
                $this->comments = $comments;
                $strComment = $this->fetch( 'Video:comment' );
                $data['content'] = $strComment;
            }else {
                $data['content'] = $comments;
            }

        }

        return $data;
    }
    /**
     * 分享按钮,用于页面iframe嵌入
     * author Hzh
     */
    public function share() {
        $data = I('');
        $data['pic'] = urldecode($data['pic']);
        $video = A('Api/Video', 'Event')->info($data['id']);
        $data['url'] = $video['type'] ? U('Home/Match/detail?id='.$data['id'],'', '', true) : C('DOMAIN').'/index.php#/video/'.intval($data['id']);
        $this->data = $data;
        $this->display();
    }
    /**
     * 根据栏目标识随机取栏目下的视频数据
     *
     * @author susy.liang<liangling@ilongyuan.com.cn>
     */
    public function randVideo() {

        $id = I( 'id' );
        $map = array();
        if ( is_numeric( $id ) ) {
            $map = array( 'topics'=>intval( $id ) );
        }

        $vEvent = A( 'Api/Video', 'Event' );
        $video_ids = $vEvent->randomLists( $map, 5 );

        $fieldMap =  array( 'id', 'title', 'thumb', 'pre_uri', 'uri', 'time', 'detail',
            'create_time', 'game_id', 'game', 'uid', 'user', 'statis', 'tags',
            'action', 'icons', 'type'
        );
        $lists = $this->lists_format( $video_ids, $fieldMap );
        if ( $lists ) {
            $this->videos = $lists;
            $content = $this->fetch( 'Template:topicvideo' );
        }

        $this->ajaxReturn( array( 'state'=>0, 'info'=>'操作成功', 'data'=>array( 'content'=>$content, 'total'=>count( $lists ) ) ) );
    }

    /**
     * 后台设置的视频推荐
     *
     * @author susy.liang<liangling@ilongyuan.com.cn>
     * 
     * modify by liubo<liubo@ilongyuan.com.cn> at 2016-05-06
     * 修改内容：
     * 1.ajax方式请求时，只返回数据，不返回html
     * 2.不使用分页，随机获取数据
     */
    public function recommend() {

        $vEvent = A( 'Api/Video', 'Event' );
        $filterMap = array(
            'id', 'title', 'thumb', 'pre_uri', 'uri', 'detail',
            'user', 'statis', 'action', 'create_time'
        );

        $recommend =  $vEvent->getRecommend();
        if (!empty($recommend)) {
            shuffle($recommend);
            $recommend = array_slice($recommend, 0, 3);
            $recommend = $this->lists_format( $recommend, $filterMap, false );
        }

        if ( IS_AJAX ) {
            if ( empty( $recommend ) ) {
                $this->ajaxReturn( array( 'state'=>-2, 'info'=>'没有更多内容了' ) );
            }else {
                $this->ajaxReturn(array('state' => 0, 'info' => '操作成功', 'data' => $recommend));
            }
        }else {
            return $recommend;
        }
    }

    public function info($id = 0)
    {
        if (!$id){
            $this->ajaxReturn(['state' => -2, 'info' => '参数错误']);
        }
        $uid = 0;
        if (defined('UID')) {
            $uid = UID;
        }
        $video = event('video')->detail($id, $uid);
        if (empty($video)) {
            $this->ajaxReturn(['state' => -2, 'info' => '参数错误']);
        }
        $this->ajaxReturn(['state' => 0, 'data' => $video]);
    }
}